package at.fhooe.SRWCProject.Bluetooth.Socket;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import at.fhooe.SRWCProject.Bluetooth.ChatActivity;
import at.fhooe.SRWCProject.MainActivity;

import java.io.InputStream;
import java.io.OutputStream;

public class ConnectionThread extends Thread{
    public BluetoothSocket mmBluetoothSocket;
    private final Handler mmHandler;
    private InputStream mmInStream;
    private OutputStream mmOutStream;

    public ConnectionThread(BluetoothSocket socket, Handler handler){
        super();
        mmBluetoothSocket = socket;
        mmHandler = handler;
        try{
            mmInStream = mmBluetoothSocket.getInputStream();
            mmOutStream = mmBluetoothSocket.getOutputStream();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run(){
        byte[] buffer = new byte[1024];
        int len;
        while (true){
            try{
                len = mmInStream.read(buffer);
                String data = new String(buffer, 0, len);
                mmHandler.obtainMessage(MainActivity.DATA_RECEIVED, data).sendToTarget();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    public void write(byte[] bytes){
        try{
            mmOutStream.write(bytes);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
